<?php
namespace App\Admin\Controllers\Shipping;

use App\Admin\Actions\Shipping\ImportApply;
use App\Admin\Actions\Shipping\SkuBatchRevoke;
use App\Admin\Ajax\Shipping\SkuAjax;
use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Basics\SysIArea;
use App\Models\Inventory\PublicCn;
use App\Models\Product\ProductClassify;
use App\Models\Shipping\SSku;
use App\Models\Shipping\SSkuApply;
use App\Models\SsBasic\AreaSku;
use Encore\Admin\Admin as RAdmin;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Request;

class SkuController extends AdminController{

    protected $title = '提货产品';

    protected function grid()
    {
        RAdmin::script($this->_script());
        $shippingDate = SSkuApply::initShippingDate();
        $sDate = array_key_first($shippingDate);
        $eDate = array_key_last($shippingDate);
        $grid = new Grid(new SSku());
        $grid->model()->where('enable_status',1)->collection(function (Collection $collection) use ($shippingDate,$sDate,$eDate){
            foreach($collection as $index => $item) {
                $item->cnp_instant_num = PublicCn::getInstant($item->psku_id);
                $applyNum = SSkuApply::getApplyNum($item->area_id,$item->psku_id,$sDate,$eDate);
                $applyNumTotal = 0;
                foreach ($shippingDate as $date => $label){
                    $item->{'apply_num'.$label} = array_key_exists($date,$applyNum) ? $applyNum[$date] : 0;
                    $applyNumTotal += $item->{'apply_num'.$label};
                }
                $item->diff_num = ($item->stock->cn_transit_num ?? 0) - $applyNumTotal;
//                $item->shipping_factor = SSku::getShippingFactor($item,$item->cnp_instant_num,$applyNumTotal);
            }
            return $collection;
        });
        $grid->column('sku.psku_cn','产品名称');
        $grid->column('area.area','站点');
        $grid->column('sku.psku_code','SKU');
        $grid->column('skuClassify.season','季节性')->using(ProductClassify::$_season);
        $grid->column('area_sku.type','来源')->display(function ($value){
            return $value ? AreaSku::$_type[$value] : '';
        });
        $grid->column('skuClassify.title','品类');
        $grid->column('_avg.avg3','3天AVG')->default(0);
        $grid->column('_avg.avg7','7天AVG')->default(0);
        $grid->column('_avg.avg15','15天AVG')->default(0);
        $grid->column('_avg.avg30','30天AVG')->default(0);
        $grid->column('_avg.avg','AVG')->default(0);
        $grid->column('stock.fba_instant_num','FBA在库')->default(0);
        $grid->column('stock.fba_transit_num','FBA在途')->default(0);
        $grid->column('cnp_instant_num','公共在库')->default(0);
        $grid->column('stock.cn_instant_num','国内在库')->default(0);
        $grid->column('stock.cn_transit_num','国内在途')->default(0);
        $grid->column('stock.os_instant_num','海外仓在库')->default(0);
        $grid->column('stock.os_transit_num','海外仓在途')->default(0);
        $grid->column('purchase_cycle','生产周期');
        $grid->column('air_day','空运时效');
        $grid->column('sea_day','海运时效');
        $grid->column('air_factor','空运提货库存系数')->view('shipping.sku.factor')->help('安全系数和目前系数，总数：所有库存(含公共库存)-国内在途');
        $grid->column('sea_factor','海运提货库存系数')->view('shipping.sku.factor')->help('安全系数和目前系数，总数：所有库存(含公共库存)-国内在途');
//        $grid->column('shipping_factor','提货系数')->help('总数：所有库存(含公共库存)-国内在途+总需求');
        foreach ($shippingDate as $label){
            $grid->column('apply_num'.$label,$label.'需求');
        }
        $grid->column('diff_num','差值')->help('在途数量-提货总数');
        $grid->column('is_lock','锁状态')->display(function ($value){
            return SSku::$_isLock[$value];
        });
        $grid->column('status','状态')->display(function ($value){
            return SSku::$_status[$value];
        });
        if(Admin::user()->can('shipping.sku.edit')){
            $grid->column('操作')->view('shipping.sku.action');
            $grid->tools(function (Grid\Tools $tools) {
                $tools->append(new ImportApply());
            });
            $grid->batchActions(function ($batch) {
                $batch->disableDelete();
                $batch->add(new SkuBatchRevoke());
            });
        }else{
            $grid->disableBatchActions();
        }
        $grid->disableExport();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('shipping/sku-download'));
        });
        $grid->disableActions();
        $grid->disableCreateButton();
        $grid->fixColumns(4,-3);
        $grid->paginate(10);
        $grid->filter(function($filter){
            $filter->column(1/3, function ($filter) {
                $filter->where(function ($query) {
                    $query->whereHas('sku', function ($query) {
                        $query->where('psku_code', 'like', "%{$this->input}%")
                            ->orWhere('psku_cn', 'like', "%{$this->input}%");
                    });
                }, 'SKU','sku8')->placeholder('模糊查询SKU，名称');
                $filter->equal('area_id','站点')->select(SysIArea::options());
            });
            $filter->column(1/3, function ($filter){
                $filter->equal('skuClassify.season', '季节性')->select(ProductClassify::$_season);
                $filter->equal('sku.classify_id', '品类')->select(ProductClassify::options());
            });
            $filter->column(1/3, function ($filter) {
                $filter->equal('status', '状态')->select(SSku::$_status);
                $filter->equal('area_sku.type', '来源')->select(AreaSku::$_type);
            });
        });

        return $grid;
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new SkuAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function modal(){
        $action = request('action');
        $param = request('param');
        $modal = new SkuAjax();
        return $param ? call_user_func([$modal,$action],$param) : call_user_func([$modal,$action]);
    }

    protected function _script()
    {
        $token = csrf_token();

        return <<<EOT
$('.apply-modal').on('click', function(e) {
    e.preventDefault();
    var id = $(this).data('id');
    $("#tempModal").modal({
        remote : '/xqc/shipping/sku-modal?param=' + id + '&action=apply'
    });
});

$("#tempModal").on("hidden.bs.modal", function() {
    $(this).removeData("bs.modal");
    $(this).find(".modal-content").children().remove();
});

var _ajaxConfirm = function(action,param,resolve){
    $.ajax({
        method: 'post',
        url: '/xqc/shipping/sku-ajax',
        data: {
            _token: "{$token}",
            action: action,
            param: param
        },
        success: function (data) {
            resolve(data);
        }
    });
};
//撤回
$('.grid-check-revoke').unbind('click').click(function(e) {
    e.preventDefault();
    var id = $(this).data('id');
    swal({
        title: "确定撤回？",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        showLoaderOnConfirm: true,
        cancelButtonText: "取消",
        preConfirm: function() {
            return new Promise(function(resolve) {
                _ajaxConfirm('revoke',id,resolve)
            });
        }
    }).then(function(result) {
        var data = result.value;
        if (typeof data === 'object') {
            if (data.status) {
                toastr.success('提交成功 !');
                $.pjax.reload('#pjax-container');
            } else {
                swal(data.message, '', 'error');
            }
        }
    });
});
EOT;
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = SSku::query()->orderBy('id', 'DESC');
        foreach ($filters as $key => $_filter){
            if($key == 'sku8'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('psku_code', 'like', "%{$_filter}%")
                        ->orWhere('psku_cn', 'like', "%{$_filter}%");
                });
            }
            if($key == 'sku'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('classify_id', $_filter['classify_id']);
                });
            }
            if($key == 'area_sku'){
                $query->whereHas('area_sku', function ($query) use($_filter){
                    $query->where('type', $_filter['type']);
                });
            }
            if($key == 'skuClassify'){
                $query->whereHas('skuClassify', function ($query) use($_filter){
                    $query->where('season', $_filter['season']);
                });
            }
            if(in_array($key,['area_id','status'])){
                $query->where($key,$_filter);
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        $shippingDate = SSkuApply::initShippingDate();
        SSku::exeDownload($query,$shippingDate);
    }
}
